//-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// simple crc function - generates lookup table on first call
#include "crc.h"
static GUINT32 crcTable[256];
static bool crcTableValid;

void calculateCRCTable()
{
   GUINT32 val;

   for(GINT32 i = 0; i < 256; i++)
   {
      val = i;
      for(GINT32 j = 0; j < 8; j++)
      {
         if(val & 0x01)
            val = 0xedb88320 ^ (val >> 1);
         else
            val = val >> 1;
      }
      crcTable[i] = val;
   }

   crcTableValid = true;
}


//-----------------------------------------------------------------------------

GUINT32 calculateCRC(const void * buffer, GINT32 len, GUINT32 crcVal )
{
   // check if need to generate the crc table
   if(!crcTableValid)
      calculateCRCTable();

   // now calculate the crc
   char * buf = (char*)buffer;
   for(GINT32 i = 0; i < len; i++)
      crcVal = crcTable[(crcVal ^ buf[i]) & 0xff] ^ (crcVal >> 8);
   return(crcVal);
}

